/**
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.taishi.library.util;

/**
 * ex.
 * AnimatorValueUtil animatorValueUtil = new AnimatorValueUtil();
 * animatorValueUtil.ofFloat(0.1f,-3f,2f)
 * public void onUpdate(AnimatorValue animatorValue, float v) {
 * float currentV = animatorValueUtil.getValue(v);
 * }
 *
 * @author name
 * @since 2021-04-06
 */
public class AnimatorValueUtil {
    private static final String TAG = "AnimatorValueUtil";
    private final int rateSize = 2;
    private final int negative = -1;
    private float[] values;
    private float[][] rate;
    private float currentValue;

    /**
     * 如传一个参数，则getValue 返回值与传入的 V 值一致
     * 如传入连续两个相同参数，则会出现除0异常
     * 传参试例: 0.8f,-1.2f,3.5f,0,5
     *
     * @param tempValues 说明
     */
    public void ofFloat(float... tempValues) {
        this.values = tempValues;
        rate = new float[this.values.length - 1][rateSize];
        float sum = 0;
        for (int ii = 1; ii < this.values.length; ii++) {
            sum += Math.abs(this.values[ii] - this.values[ii - 1]);
        }

        for (int ii = 0; ii < rate.length; ii++) { // 计算每个变化值的占比和达到该变化值系数
            float tempRate = Math.abs((this.values[ii + 1] - this.values[ii]) / sum);
            rate[ii][0] = tempRate + (ii == 0 ? 0 : rate[ii - 1][0]);
            float tempDuration = this.values[ii + 1] - this.values[ii];
            rate[ii][1] = (this.values[ii] > this.values[ii + 1] ? negative : 1) * Math.abs(tempDuration / tempRate);
        }
    }

    /**
     * 根据 属性动画中value的值，计算当前值
     *
     * @param value 属性动画中的value
     * @return 通过计算后的值
     */
    public float getValue(float value) {
        currentValue = value;
        for (int ii = 0; ii < rate.length; ii++) {
            // 如果是进入当前变化值占比，则按当前系数进行计算实际值(bounce回弹效果最后v会大于1)
            if (value <= rate[ii][0] || value > 1) {
                currentValue = values[ii] + (ii == 0 ? value : value - rate[ii - 1][0]) * rate[ii][1];
                return currentValue;
            }
        }
        return value;
    }

    public float getCurrentValue() {
        return currentValue;
    }
}
